/**
 * 解析 URL 参数
 * @param url URL字符串
 * @returns {Object} 参数对象
 */
export const parseUrlParams = (url) => {
  const params = {}
  if (!url || url.indexOf('?') === -1) return params

  const queryString = url.split('?')[1]
  const paramPairs = queryString.split('&')

  paramPairs.forEach(pair => {
    const [key, value] = pair.split('=')
    if (key) {
      params[decodeURIComponent(key)] = decodeURIComponent(value || '')
    }
  })

  return params
}

/**
 * 构建 URL 参数字符串
 * @param params 参数对象
 * @returns {string} 参数字符串
 */
export const buildUrlParams = (params) => {
  if (!params || typeof params !== 'object') return ''

  const pairs = []
  Object.keys(params).forEach(key => {
    const value = params[key]
    if (value !== undefined && value !== null) {
      pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    }
  })

  return pairs.length ? `?${pairs.join('&')}` : ''
}

/**
 * 合并基础 URL 和参数
 * @param baseUrl 基础URL
 * @param params 参数对象
 * @returns {string} 完整URL
 */
export const buildFullUrl = (baseUrl, params) => {
  if (!baseUrl) return ''
  const paramString = buildUrlParams(params)
  return baseUrl + paramString
}

/**
 * 获取URL的域名部分
 * @param url URL字符串
 * @returns {string} 域名
 */
export const getDomain = (url) => {
  if (!url) return ''
  try {
    const urlObj = new URL(url)
    return urlObj.hostname
  } catch (e) {
    return ''
  }
}

export default {
  parseUrlParams,
  buildUrlParams,
  buildFullUrl,
  getDomain
}
